<?php

namespace App\Http\Controllers\Admin\Articles\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Common\CommonApi;
use App\Model\Articles;
use Illuminate\Support\Facades\Redis;

class ArticlesApi extends Controller
{   
    /**
     * 获取文章列表
     * @return [type] [description]
     */
    public static function getArticlesList($type = 'all')
    {   
        if ($type == 'all') {

            if (Redis::keys('articles-list-all')) {
            
                return json_decode(Redis::get('articles-list-all'), true);
            }

            $articlesList = Articles::select(['id', 'category_id', 'title', 'author', 'cover', 'is_top', 'click', 'display', 'description', 'updated_at', 'created_at'])
                            ->orderBy('is_top', 'desc')->latest()->get()->toArray();

            Redis::set('articles-list-all', json_encode($articlesList));

            return $articlesList;

        } else if ($type == 'active') {

            if (Redis::keys('articles-list-active')) {

                return json_decode(Redis::get('articles-list-active'), true);
            }

            $articlesList = Articles::select(['id', 'category_id', 'title', 'author', 'cover', 'is_top', 'click', 'display', 'description', 'updated_at', 'created_at'])
                            ->where('display', 1)->orderBy('is_top', 'desc')->latest()->get()->toArray();

            Redis::set('articles-list-active', json_encode($articlesList));

            return $articlesList;
        }
        
    }


    /**
     * 执行文章添加,存入数据库
     * @param  Request $request [用户填写的信息]
     * @return [array]           [执行后的结果]
     */
    public static function doArticleAdd(Request $request)
    {
        //获取用户输入的文章信息
        $categoryID = $request->input('category');
        $tagIDs = $request->input('tags');  //是数组
        $title = $request->input('title');
        $author = $request->input('author');
        $keywords = ($request->input('keywords') == null) ? '' : $request->input('keywords');
        $is_top = $request->input('is_top');
        $display = $request->input('display');
        $description = ($request->input('description') == null) ? '' : $request->input('description');
        $html = ($request->input('html') == null) ? '' : $request->input('html');
        $content = ($request->input('content') == null) ? '' : $request->input('content');
        $click = 0;

        //把封面图上传到七牛云,并且获取图片链接
        //判断是否有封面图上传
        if ($request->file('cover') !== null) {
            //如果有封面图上传,则录入到七牛云
//            $picInfo = CommonApi::uploadToQiNiu($request, 'cover');

//            if ($picInfo['code'] == 400) {
//                //如果上传图片失败,返回去
//                return [
//                    'code' => 400,
//                    'msg' => '上传封面图失败',
//                ];
//            }

            //获取封面图片的链接
//            $cover = 'http://' . env('QINIU_DOMAIN') . '/' . $picInfo['data']['key'];

            $picName = 'cover' . date('YmdHis') . '.jpg';
            $cover = $request->cover->storeAs('images/cover', $picName);

        } else {
            //=================== 如果没有上传,默认某张图片作为封面图 =====================
            $cover = 'http://' . env('QINIU_DOMAIN') . '/mmexport1474637684526.jpg';
        }
        
        //执行录入数据库
        $articleModel = new Articles;

        $articleModel->category_id = $categoryID;
        $articleModel->title = $title;
        $articleModel->author = $author;
        $articleModel->content = $content;
        $articleModel->html = $html;
        $articleModel->description = $description;
        $articleModel->keywords = $keywords;
        $articleModel->cover = $cover;
        $articleModel->is_top = $is_top;
        $articleModel->click = $click;
        $articleModel->display = $display;

        $bool = $articleModel->save();

        if ($bool) {
            //录入文章与标签的关系表
            $articleModel->findTags()->attach($tagIDs);

            //======  待完善: 从七牛云删除"因为在编辑过程中删掉而没有录入数据库"的那些图片
            


            //返回结果
            return [
                'code' => 200,
                'msg' => '新增博客成功',
            ];
            
        } else {

            return [
                'code' => 400,
                'msg' => '新增博客失败',
            ];
        }


    }


    public static function doArticleUpdate(Request $request)
    {
        //获取用户输入的文章信息
        $articleID = $request->input('id');
        $categoryID = $request->input('category');
        $tagIDs = $request->input('tags');  //是数组
        $title = $request->input('title');
        $author = $request->input('author');
        $keywords = ($request->input('keywords') == null) ? '' : $request->input('keywords');
        $is_top = $request->input('is_top');
        $display = $request->input('display');
        $description = ($request->input('description') == null) ? '' : $request->input('description');
        $html = ($request->input('html') == null) ? '' : $request->input('html');
        $content = ($request->input('content') == null) ? '' : $request->input('content');

        //获取文章的原来模型
        $articleModel = Articles::find($articleID);

        //如果有新的封面图上传,则上传新的图片,没有则维持不变
        if ($request->file('cover') !== null) {
            //上传到七牛云
//            $picInfo = CommonApi::uploadToQiNiu($request, 'cover');
//
//            if ($picInfo['code'] == 400) {
//                //如果上传图片失败,返回去
//                return [
//                    'code' => 400,
//                    'msg' => '上传封面图失败',
//                ];
//            }


            //============= 待完善,从七牛云中删除原来封面图的图片
            




            //获取新封面图片的链接
//            $cover = 'http://' . env('QINIU_DOMAIN') . '/' . $picInfo['data']['key'];

            $picName = 'cover' . date('YmdHis') . '.jpg';
            $cover = $request->cover->storeAs('images/cover', $picName);

            $articleModel->cover = $cover;
        }

        //=====  待完善:获取原来文章详情中的所有图片地址(使用正则)
        preg_match_all('/src=\"(.*?)\"/', $html, $match);   //注意$match[1]才是纯图片地址,这是一个数组
        // dd($match);

        //执行录入数据库
        $articleModel->category_id = $categoryID;
        $articleModel->title = $title;
        $articleModel->author = $author;
        $articleModel->content = $content;
        $articleModel->html = $html;
        $articleModel->description = $description;
        $articleModel->keywords = $keywords;
        $articleModel->is_top = $is_top;
        $articleModel->display = $display;

        $bool = $articleModel->save();

        if ($bool) {

            //=====  待完善:把文章详情中没有用的旧图片地址从七牛云中删除


            //删除该文章与标签的全部关系
            \DB::table('articles_tags')->where('article_id', $articleID)->delete();

            //录入文章与标签的关系表
            $articleModel->findTags()->attach($tagIDs);

            //======  待完善: 从七牛云删除"因为在编辑过程中删掉而没有录入数据库"的那些图片
            


            //返回结果
            return [
                'code' => 200,
                'msg' => '修改博客成功',
            ];
            
        } else {

            return [
                'code' => 400,
                'msg' => '修改博客失败',
            ];
        }

    }


    public static function getArticleDetail($id)
    {
        $article = Articles::select(['id', 'category_id', 'title', 'author', 'html', 'description', 'keywords', 'cover', 'is_top', 'click', 'created_at', 'updated_at'])
            ->where('id', $id)->first()->toArray();

        return $article;
    }


    public static function addArticleClick($id)
    {   
        //先把增加阅读量存入Redis,然后再用定时任务把阅读量录入数据库
        if (Redis::hExists('article-click-number:id', $id)) {
            //如果键已经存在,则点击量+1
            Redis::hIncrBy('article-click-number:id', $id, 1);
        } else {
            //否则设定点击增量为1
            Redis::hSet('article-click-number:id', $id, 1);
        }

        //存储点击过的文章id
        Redis::sAdd('article-clicked:id', $id);
    }


}
